package com.cooba.video_frament;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.BannerDetailsActivity;
import com.cooba.adapter.VideoAdapter;
import com.cooba.application.MyApplication;
import com.cooba.bean.BannerBean;
import com.cooba.bean.BannerStatistic;
import com.cooba.bean.VideoBeans;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.views.BannerLayout;
import com.cooba.views.loadview.LoadViewHelper;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qq.e.comm.util.StringUtil;
import com.ta.utdid2.android.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wangkun
 * @Date : 2016/5/31 13:43
 * @Description :视频类基础Fragment
 */
public abstract class VideoBaseFragment extends Fragment {
    protected LoadViewHelper helper;// 加载过程动画

    public static final int SAVE_TIME = 60 * 60 * 24 * 30;//数据保存一个月
    private List<BannerStatistic.BannerInfo> bannerInfoList = new ArrayList<>();
    public String index="";
    protected Boolean isIncar;
    protected String mac;
    public HttpUtils httpUtils;
    public RequestParams params;
    public VideoAdapter mAdapter;
    public PullToRefreshListView rListView;
    public BannerBean banner;
    private List<VideoBeans.VideoListEntity> list = new ArrayList<>();
    private boolean mIsFirstLoad=true;


    public View getCustomHeaderView(final Context context, final List<BannerBean.BannerListEntity> bannerlist) {
        View headerView = View.inflate(context, R.layout.view_custom_header, null);
        final BannerLayout bannerLayout = (BannerLayout) headerView.findViewById(R.id.banner);
        int width = context.getResources().getDisplayMetrics().widthPixels;
        int height = (int) (width * 0.56);
        bannerLayout.setLayoutParams(new LinearLayout.LayoutParams(width, height));
        final List<String> urls = new ArrayList<>();
        for (int i = 0; i < bannerlist.size(); i++) {
            urls.add(bannerlist.get(i).getHome_pic());
        }
        bannerLayout.setViewUrls(urls);

//        getBannerStatistic(bannerlist.get(0),"0");
        //添加监听事件
        bannerLayout.setOnBannerStatisticListener(new BannerLayout.OnBannerStatisticListener() {
            @Override
            public void onBannerStatistic(int position) {
                //切换一次 拼装一次广告数据
               if (position<bannerlist.size()) {
//                   getBannerStatistic(bannerlist.get(position),"1");
               }

            }
        });
        bannerLayout.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //Toast.makeText(context, String.valueOf(position), Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(getContext(), BannerDetailsActivity.class);
                intent.putExtra("bannerurl",bannerlist.get(position).getHref());
                startActivity(intent);
//                getBannerStatistic(bannerlist.get(position),"0");
            }
        });
        return headerView;
    }

    //获取广告统计信息
    public void getBannerStatistic(BannerBean.BannerListEntity bannerEntity,String eventtype) {

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String happenTime = sDateFormat.format(new java.util.Date());
        String mac = CommonUtil.getMacAddress(getContext());
        String ip = CommonUtil.getLocalIpAddress(getContext());
        String xLine = CommonUtil.getLocation(getContext(), 0);//经度
        String yLine = CommonUtil.getLocation(getContext(), 1);//纬度
        String clientOs = "Android";
        String clientType = android.os.Build.VERSION.RELEASE;
        String login_id = SharedPreferencesUtil.getData(getContext(), "login_id", "");
        String username = "";
        String netType;
        if ( MyApplication.getMyApplication().getIsInCar()){
            netType ="0";
        }else {
            netType="1";
        }
        String platform = "0";

        String bannerId = bannerEntity.getId();
        String name = bannerEntity.getName();
        String path = bannerEntity.getPath();
        String payType = bannerEntity.getPay_type();
        String eventType = eventtype;

        BannerStatistic.BannerInfo bannerInfo = new BannerStatistic.BannerInfo();
        bannerInfo.setMac(mac);
        bannerInfo.setIp(ip);
        bannerInfo.setClientOs(clientOs);
        bannerInfo.setClientType(clientType);
        bannerInfo.setLoginId(login_id);
        bannerInfo.setUserName(username);
        bannerInfo.setNetType(netType);
        bannerInfo.setxLine(xLine);
        bannerInfo.setyLine(yLine);
        bannerInfo.setHappenTime(happenTime);
        bannerInfo.setPlatform(platform);
        bannerInfo.setBannerId(bannerId);
        bannerInfo.setName(name);
        bannerInfo.setPath(path);
        bannerInfo.setPayType(payType);
        bannerInfo.setEventType(eventType);

        bannerInfoList.add(bannerInfo);
        Log.d("wei", "Json数据1:" + new Gson().toJson(bannerInfo));
        CommonUtil.writeTxtToFile(new Gson().toJson(bannerInfo));

        BannerStatistic bannerStatistic = new BannerStatistic();
        bannerStatistic.setStatisticsList(bannerInfoList);
        Log.d("wei", "Json数据2:" + new Gson().toJson(bannerStatistic));
    }



    public String judgeVideoUrl(){
        String urlVideo;
        if (isIncar) {
            urlVideo = "http://a.cooba.cc/Port/videoPortInfo";
        } else {
            urlVideo = ServerURL.httpUrl + ServerURL.queryVideoList;
        }
        return urlVideo;
    }

    public String judgeBannerUrl(){
        String urlVideo;
        if (isIncar) {
            urlVideo = "http://a.cooba.cc/banner";
        } else {
            urlVideo = ServerURL.httpUrl + ServerURL.bannerList;
        }
        return urlVideo;
    }

    public void initIncar() {
        MyApplication application = MyApplication.getMyApplication();
        isIncar = application.getIsInCar();
        mac = application.getMac();
    }





    public void getData(final String dirName,final boolean isfenye) {
        if (mIsFirstLoad){
            helper.showLoading("正在加载...");
        }

        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", dirName);
        params.addBodyParameter("next_key", "0");
        params.addBodyParameter("page_size", "10");
        httpUtils.send(HttpRequest.HttpMethod.POST, judgeVideoUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("video视频：", "获取失败");
                //从缓存中读取数据
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wangkun", "获取成功" + responseInfo.result);
                paserData(dirName,responseInfo.result, isfenye);
            }
        });

    }
    public void getDataUp(String next_key, final String dirName,final boolean isfenye) {
     /*   if(next_key==null || StringUtils.isEmpty(next_key)){
            Toast.makeText(getContext(), "暂时没有新数据啦", Toast.LENGTH_SHORT).show();
            return;
        }*/
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", dirName);
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");


        httpUtils.send(HttpRequest.HttpMethod.POST, judgeVideoUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("sss", "获取失败");
                rListView.onPullUpRefreshComplete();
                rListView.onPullDownRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                paserData(dirName,responseInfo.result, isfenye);
                rListView.onPullUpRefreshComplete();
                rListView.onPullDownRefreshComplete();
            }

        });

    }

    //解析数据并添加到集合
    public void paserData(final String dirName,String result, final boolean isfenye) {
       /* if (!isfenye) {
            list.clear();
        }*/

        VideoBeans shitingBean = new Gson().fromJson(result, VideoBeans.class);
        if (shitingBean.getVideoList()!=null&&shitingBean.getVideoList().size()>0) {
            index = String.valueOf(shitingBean.getNext_key());
            if (mAdapter == null) {
                mAdapter = new VideoAdapter(getActivity(), shitingBean.videoList);
                rListView.getRefreshableView().setAdapter(mAdapter);
                mIsFirstLoad = false;
                helper.restore();
            } else {
                mAdapter.getList().addAll(mAdapter.getList().size(), shitingBean.videoList);
                mAdapter.setList(mAdapter.getList());
            }
            if (shitingBean.getVideoList().size() < 10) {
                rListView.setHasMoreData(false);
            }
        }else {
            if (!isfenye){
                helper.showEmpty("暂时没有数据", "重新加载",true, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        helper.restore();
                        getData(dirName,isfenye);
                    }
                });
            }else {
                Toast.makeText(getContext(), "没有更多数据啦", Toast.LENGTH_SHORT).show();
            }
        }
        rListView.onPullDownRefreshComplete();
        rListView.onPullUpRefreshComplete();
    }

    public void savaVideoHistory(VideoBeans.VideoListEntity entity){
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String watch_date = sDateFormat.format(new java.util.Date());
        entity.setWatch_time(watch_date);
        List<VideoBeans.VideoListEntity> list=CommonUtil.getVideoHistoryList(getContext());
        if (list==null){
            list=new ArrayList<>();
            list.add(0,entity);
            CommonUtil.setVideoHistoryList(getContext(),list);
        }else {
            if (list.contains(entity)){
                list.remove(entity);
            }
            list.add(0,entity);
            CommonUtil.setVideoHistoryList(getContext(), list);
        }
        for (int i=0;i<list.size();i++){
            Log.d("wei","数据:"+list.get(i).getTitle());
        }
    }



    protected class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            rListView.onPullUpRefreshComplete();
            rListView.onPullDownRefreshComplete();
        }
    }
    /**
     * @param view
     *            需要过载动画覆盖的view
     */
    public void initLoadViewHelper(View view) {
        helper = new LoadViewHelper(view);
    }
}
